<template>
  <div class="wechatPlatformBox">
    <div>
      <div class="title">{{$t('configLazyLoad.channel.wexinTip93')}}</div>
      <div class="remark_title">
        {{$t('configLazyLoad.channel.wexinTip94')}}{{$store.state.oemObj.oemFlag ? $t('configLazyLoad.channel.wexinTip95') : $t('configLazyLoad.channel.wexinTip96')}}{{$t('configLazyLoad.channel.wexinTip97')}}
      </div>
      <el-form class="platform-form-box" ref="ruleForm" :rules="rules" :model="form"  label-position="left" label-width="210px">
        <!-- 微信名称 -->
        <el-form-item :label="$t('configLazyLoad.channel.wechatName')" prop="nick_name">
          <el-input v-model.trim="form.nick_name"></el-input>
        </el-form-item>
        <!-- 微信AppId(开发者ID) -->
        <el-form-item :label="$t('configLazyLoad.channel.wexinTip98')" prop="appid">
          <el-input :disabled="todoType === 'add' ? false : true" v-model.trim="form.appid"></el-input>
        </el-form-item>
        <!-- 开发者密码(AppSecret) -->
        <el-form-item :label="$t('configLazyLoad.channel.wexinTip99')" prop="appSecret">
          <el-input type="password" v-model.trim="form.appSecret"></el-input>
        </el-form-item>
        <!-- 授权码(access_token)获取url接口 -->
        <el-form-item :label="$t('configLazyLoad.channel.wexinTip100')" class="" prop="access_token_url">
          <el-input v-model.trim="form.access_token_url"></el-input>
          <question-tooltip
                  class="wechatPlatformTooltip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.wexinTip101')">
          </question-tooltip>
        </el-form-item>
        <!-- 是否启用日程 -->
        <el-form-item :label="$t('configLazyLoad.channel.wexinTip22')" prop="scheduleEnable" style="text-align: left">
          <el-radio-group v-model.trim="form.scheduleEnable">
            <el-radio :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
            <el-radio :label="true">{{$t('config.channel.enabled')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <p class="remark_title">{{$t('configLazyLoad.channel.wexinTip23')}}</p>
        <!-- 消息分发技能组 -->
        <el-form-item v-show="!form.scheduleEnable" :label="$t('config.channel.msgToPeer')" prop="to_peer">
          <el-select size="mini" v-model.trim="form.to_peer" :placeholder="$t('public.pleasePick')">
            <el-option
                    v-for="(item, index) in peerOptions"
                    :key="index"
                    :label="item.DisplayName"
                    :value="item.Exten"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 启用智能机器人 -->
        <el-form-item v-show="!form.scheduleEnable"  :label="$t('config.channel.isUseRobt')" prop="robot">
          <el-select size="mini" v-model.trim="form.robot" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
            <el-option value="">{{$t('public.pleasePick')}}</el-option>
            <el-option
                    v-for="item in allrobotOptions"
                    :key="item._id"
                    :label="item.robot_name_new"
                    :disabled="item.disabled"
                    :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 机器人辅助座席 -->
        <el-form-item v-show="!form.scheduleEnable && aiRobots.length > 0"  :label="$t('configLazyLoad.channel.robotAssistId')" prop="robotAssistId">
          <el-select size="mini" v-model.trim="form.robotAssistId" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
            <el-option value="">{{$t('public.pleasePick')}}</el-option>
            <el-option
                    v-for="item in aiRobots"
                    :key="item._id"
                    :label="item.robot_name_new"
                    :disabled="item.disabled"
                    :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 是否开启触发词命中转人工 -->
        <el-form-item :label="$t('configLazyLoad.channel.turnTip3')" prop="openTriggerWord" style="text-align: left">
          <el-radio-group v-model.trim="form.openTriggerWord">
            <el-radio :label="true">{{$t('public.yes')}}</el-radio>
            <el-radio :label="false">{{$t('public.no')}}</el-radio>
          </el-radio-group>
          <question-tooltip
                  class="wechatPlatformTooltip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.turnTip4')">
          </question-tooltip>
        </el-form-item>
        <!-- 转人工触发词 -->
        <el-form-item :label="$t('config.channel.userPeopleWord')" prop="convert_words">
          <el-input size="mini" v-model.trim="form.convert_words" :placeholder="$t('configLazyLoad.channel.turnTip5')"></el-input>
          <question-tooltip
                  class="wechatPlatformTooltip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.turnTip6')">
          </question-tooltip>
        </el-form-item>
        <!-- 欢迎语推送时机 -->
        <el-form-item v-show="!form.scheduleEnable" :label="$t('config.channel.sendWelcomeMsg')" prop="welcomePushTime" style="text-align: left">
          <el-radio-group v-model="form.welcomePushTime" @change="pushTimeChange">
            <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
            <el-radio class="radio welcome-radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 欢迎语 -->
        <el-form-item v-show="!form.scheduleEnable"  :label="$t('config.channel.welcomeMsg')" prop="welcome_msg">
          <span class="remark">{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
          <question-tooltip
                  class=""
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.wexinTip102')">
          </question-tooltip>
          <div class="placeholder_box">
            <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
              {{place.content}}
              <i class="iconfont icon-zhankai"></i>
            </dl>
          </div>
          <el-input size="mini" type="textarea" v-model="form.welcome_msg"></el-input>
        </el-form-item>
        <!-- 是否启用满意度评价 -->
        <el-form-item :label="$t('config.channel.isUseSatisfaction')" prop="csr" style="text-align: left">
          <el-radio-group v-model.trim="form.webchat_csr">
            <el-radio class="radio" :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
            <el-radio lass="radio welcome-radio" :label="true">{{$t('config.channel.enabled')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('config.channel.authorizationPush')" prop="snsapiUserinfoFlag" style="text-align: left;">
          <el-radio-group v-model.trim="form.snsapiUserinfoFlag">
            <el-radio :label="true">{{$t('public.yes')}}</el-radio>
            <el-radio :label="false">{{$t('public.no')}}</el-radio>
          </el-radio-group>
         <question-tooltip
                  class="wechatPlatformTooltip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.turnTip8')">
          </question-tooltip>
        </el-form-item>
      </el-form>
      <div class="btn" v-if="todoType === 'add'">
        <el-button class="primary_btn" style="margin-right: 20px" @click="cancelType(1)">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="nextStep(1)">{{$t('public.nextStep')}}</el-button>
      </div>
      <div class="btn" v-if="!todoType">
        <el-button type="primary" class="primary_btn" @click="nextStep(2)">{{$t('public.save')}}</el-button>
      </div>
    </div>
  </div>
</template>
<script>
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  import { randomWord, deepClone } from '@/utils/m7Utils'
  export default {
    name: 'wechatPlatformStep',
    data () {
      return {
        form: {
          _id: '',                    //  数据id
          nick_name: '',              //  微信名称
          appid: '',                  //  微信AppId
          appSecret: '',              //  开发者密码
          access_token_url: '',       //  授权码(access_token)获取url接口
          scheduleEnable: false,      //  是否启用日程
          to_peer: '',                //  技能组
          robot: '',                  //  启用智能机器人
          robotAssistId: '',          //  机器人辅助座席
          openTriggerWord: true,      //  是否开启触发词命中转人工
          convert_words: '',          //  转人工触发词
          welcomePushTime: 'access',  //  欢迎语推送时机
          welcome_msg: '',            // 欢迎语
          webchat_csr: false,         //  是否启用满意度评价
          snsapiUserinfoFlag:false,
          server_url: '',             //  URL服务地址
          token: '',                  //  Token（令牌）
          ipList: [],                 //  服务IP
          encoding_AESKey: ''         //  EncodingAESKey
        },
        wechatUrl: '',                //  服务域名
        peerOptions: [],              //  技能组列表
        aiRobots: [],                 //  机器人辅助座席列表
        allrobotOptions: [],          //  智能机器人列表
        placeholderArr: [             //  欢迎语占位符
//          {
//            content: '访客ID：userId',
//            data: 'userId'
//          },
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ],
        rules: {
          nick_name: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          appid: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          appSecret: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]
//          to_peer: [
//            { required: true, message: '请选择技能组', trigger: 'change' }
//          ]
        }
//        currentStep: 'second'
      }
    },
    components: {
      questionTooltip
    },
    methods: {
      allrobotOptions (show) {
        if (show) {
          this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
            if (res2 && res2.success && res2.data && res2.data.length > 0) {
              let aiRobot = res2.data
              let allRobot = this.allrobotOptions
              aiRobot.forEach((item1) => {
                item1._id = item1.Id
                item1.robot_name_new = item1.Nick
                let exist = allRobot.findIndex((all) => {
                  return all.Id === item1.Id
                })
                if (exist === undefined) {
                  allRobot.push(item1)
                } else {
                  allRobot.splice(exist, 1, item1)
                }
              })
              this.aiRobots = aiRobot
              this.allrobotOptions = allRobot
            }
          })
        }
      },
      nextStep (step) {
        if(this.form.snsapiUserinfoFlag&&!this.form.appSecret){
          this.$message.error(this.$t('configLazyLoad.channel.robotError5'))
          return 
        }
        if (!this.peerOptions.length) {
          this.$message.error(this.$t('configLazyLoad.channel.robotError4'))
          return
        }
        let that = this
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (!that.form.to_peer && !that.form.scheduleEnable) {
              that.$message.error(this.$t('webchat.placeSkillsGrouop'))
              return
            }
            if (that.form.robot === '') {
              that.form.robotType = ''
            } else {
              that.allrobotOptions.forEach((item) => {
                if (item._id === that.form.robot) {
                  if (item.Nick) {
                    that.form.robotType = item.robotType
                  } else {
                    that.form.robotType = item.robot_type_new
                  }
                  that.form.robotname = item.robot_name_new
                }
              })
            }
//          机器人辅助座席，增加assistRobotType参数
            that.aiRobots.map((item) => {
              if (that.form.robotAssistId === item._id) {
                if (that.form.robotAssistId !== '') {
                  that.$set(that.form, 'assistRobotType', item.robotType)
                } else {
                  that.$set(that.form, 'assistRobotType', '')
                }
              }
            })
            if (step === 1) {
              that.form.server_url = that.wechatUrl + '/wxDevMode/' + that.form.appid
              that.form.encoding_AESKey = randomWord(false, 43)
              that.form.token = randomWord(false, 32)
//              that.currentStep = 'last'
              let data = that.form
              that.$emit('next', {step: 1, data: data, wechatUrl: that.wechatUrl})
            } else if (step === 2) {
              that.$store.dispatch('updateWxDevModeConfig', that.form).then((res) => {
                if (res.success) {
                  that.$message.success(this.$t('business.updateSuccess'))
                }
              })
            }
          }
        })
      },
//      previousStep () {
//        this.currentStep = 'second'
//      },
      addPlaceholder (data) {
        this.form.welcome_msg += '{' + data + '}'
      },
      cancelType (step) {
        this.$emit('cancel', step)
      },
      //  更改欢迎语推送时机
      pushTimeChange (data) {
        if (data === 'access') {
          this.placeholderArr = [
//            {
//              content: '访客ID：userId',
//              data: 'userId'
//            },
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }
          ]
          let str = deepClone(this.form.welcome_msg)
          str = str.replace(/\{agent\}/g, '')
          str = str.replace(/\{agentName\}/g, '')
          this.form.welcome_msg = str
        } else if (data === 'claim') {
          this.placeholderArr = [
//            {
//              content: '访客ID：userId',
//              data: 'userId'
//            },
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }, {
              content: this.$t('configLazyLoad.channel.agent'),
              data: 'agent'
            }, {
              content: this.$t('configLazyLoad.channel.agentName'),
              data: 'agentName'
            }, {
              content: this.$t('configLazyLoad.channel.agentNickName'),
              data: 'agentNickName'
            }, {
              content: this.$t('configLazyLoad.channel.agentPhone'),
              data: 'agentPhone'
            }
          ]
        }
      }
    },
    props: {
      todoType: String,
      weixindata: Object
    },
    mounted () {
      this.showTab = 'one'
    },
    beforeMount () {
      if (this.weixindata && this.weixindata._id) {
        this.form = deepClone(this.weixindata)
        if (this.form.openTriggerWord === undefined) {
          this.$set(this.form, 'openTriggerWord', true)
        }
        if (this.form.snsapiUserinfoFlag === undefined) {
          this.$set(this.form, 'snsapiUserinfoFlag', false)
        }
        // 判断小七是否回显
        if (this.$store.state.isM7RobotOpen === false) {
          if (this.form.robot === '5825a500dfe52d5edc6e36c9') {
            this.form.robot = ''
          }
        }
      }
      if (this.form.welcomePushTime === 'access') {
        this.placeholderArr = [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ]
      } else if (this.form.welcomePushTime === 'claim') {
        this.placeholderArr = [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }, {
            content: this.$t('configLazyLoad.channel.agent'),
            data: 'agent'
          }, {
            content: this.$t('configLazyLoad.channel.agentName'),
            data: 'agentName'
          }, {
            content: this.$t('configLazyLoad.channel.agentNickName'),
            data: 'agentNickName'
          }, {
            content: this.$t('configLazyLoad.channel.agentPhone'),
            data: 'agentPhone'
          }
        ]
      }
      this.$store.dispatch('GetWeChatDock', {_id: this._id}).then(req2 => {
        console.log(req2)
        if (req2.success) {
          let url = req2.wechatUrl
          if (url.indexOf('http://') !== -1) {
            url = url.replace('http://', '')
          }
          if (url.indexOf('https://') !== -1) {
            url = url.replace('https://', '')
          }
          this.wechatUrl = url
        }
      })
      this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
        let mailQueues = req
        this.peerOptions = mailQueues || []
      })
      this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
        let robotConfig = this.$getCache('robotConfig') || []
        this.allrobotOptions = robotConfig
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
            })
            this.aiRobots = aiRobot
            let configArr = []
            this.allrobotOptions.forEach((config) => {
              if (config.robot_type !== 'didi') {
                configArr.push(config)
              }
            })
            this.allrobotOptions = configArr.concat(this.aiRobots)
          }
        })
      })
      this.$store.dispatch('getWechatAddress', {}).then(req3 => {
        console.log(req3)
        if (req3.success) {
          console.log(req3)
          this.form.ipList = req3.data.split(',')
        }
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .title
    font-size 18px
    margin 16px 0 20px
  .wechatPlatformBox
    text-align center
    overflow auto
  .platform-form-box
    width 500px
    margin 0 auto
  .btn
    margin 20px
    text-align center
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height 16px
    text-align left
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
  .wechatPlatformTooltip
    position absolute
    right -26px
  .remark_title
    color #3b5998
    font-size 12px
    width 500px
    margin 0 auto
</style>
